<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<!-- <cl-add-btn /> -->
			<!-- 删除按钮 -->
			<!-- <cl-multi-delete-btn /> -->
			<!-- 导出按钮 -->
			<cl-export-btn :columns="Table?.columns" :data="onExportData" />
			<el-button type="info" @click="shopAddCustomerOrder">客情下单</el-button>
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table">
				<template #slot-edit-order-btn="{ scope }">
					<el-button
						v-if="scope.row.orderProgress == 2"
						type="primary"
						@click="
							() => {
								agentAddOrder(scope.row);
							}
						"
						>编辑</el-button
					>
				</template>
				<template #slot-zhongtian-order-btn="{ scope }">
					<el-button
						type="primary"
						@click="
							() => {
								agentViewOrder(scope.row);
							}
						"
						>查看</el-button
					>
				</template>
			</cl-table>
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
	<tongkang-edit-order
		v-model="ZhongtianAddOrderVisible"
		:orderObj="currentOrderObj"
		:order-id="currentOrderId"
		@closeDialog="closeDialog"
	/>
	<tongkang-view-order
		v-model="ZhongtianViewOrderVisible"
		:orderObj="currentOrderObj"
		:order-id="currentOrderId"
		@closeDialog="closeViewDialog"
	/>
	<!-- 客情处理表单组件 -->
	<shop-customer-relationship
		v-model="CustomerRelationshipVisible"
		:orderObj="currentOrderObj"
		:order-id="currentOrderId"
		@closeDialog="closeCustomerRelationshipDialog"
		@success="handleCustomerRelationshipSuccess"
	/>
<shop-customer-order :shopObj="shopObj" v-model="CustomerOrderVisible" @closeDialog="closeCustomerOrderDialog" />

</template>

<script lang="ts" setup>
defineOptions({
	name: 'order-order'
});

import { useCrud, useTable, useUpsert, useSearch } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { onMounted, reactive, ref } from 'vue';
import UserSelect from '/$/user/components/user-select.vue';
import { useBase } from '/$/base';
import TongkangViewOrder from '../components/shop-view-order.vue';
import TongkangEditOrder from '../components/tongkang-edit-order.vue';
import { ElMessage } from 'element-plus';
import ShopCustomerOrder from '../components/shop-customer-order.vue';


const { service } = useCool();
const { t } = useI18n();
const { user } = useBase();
const ZhongtianAddOrderVisible = ref(false);
const ZhongtianViewOrderVisible = ref(false);
const currentOrderObj = ref({});
const currentOrderId = ref(0);
const CustomerRelationshipVisible = ref(false);
const CustomerOrderVisible = ref(false);
const shopObj = ref({});

// 选项
const options = reactive({
	payStatus: [
		{ label: t('待支付'), value: 0 },
		{ label: t('已支付'), value: 1 },
		{ label: t('支付失败'), value: 2 },
		{ label: t('已退款'), value: 3 }
	],
	deliveryStatus: [
		{ label: t('待发货'), value: 0 },
		{ label: t('已发货'), value: 1 },
		{ label: t('运输中'), value: 2 },
		{ label: t('已签收'), value: 3 },
		{ label: t('退货中'), value: 4 },
		{ label: t('已退货'), value: 5 }
	],
	payType: [
		{ label: t('微信支付'), value: 0 },
		{ label: t('支付宝'), value: 1 },
		{ label: t('银行卡'), value: 2 },
		{ label: t('其他'), value: 3 }
	],
	orderProgress: [
		{ label: t('待门店下单'), value: 0, type: 'warning' },
		{ label: t('待下单厂家'), value: 1, type: 'warning' },
		{ label: t('已下单完成'), value: 2, type: 'success' },
		{ label: t('退货审核中'), value: 3, type: 'error' },
		{ label: t('换货审核中'), value: 4, type: 'error' },
		{ label: t('退换货审核已通过'), value: 1000, type: 'success' }
	],
	cityList: [],
	agentUser: []
});

// cl-upsert
const Upsert = useUpsert({
	items: [
		{ label: t('选择用户'), prop: 'userId', component: { vm: UserSelect } },
		{
			label: t('订单号'),
			prop: 'orderNo',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('支付状态'),
			prop: 'payStatus',
			component: { name: 'el-radio-group', options: options.payStatus },
			value: 0,
			required: true
		},
		{
			label: t('物流状态'),
			prop: 'deliveryStatus',
			component: {
				name: 'cl-select',
				props: { options: options.deliveryStatus }
			},
			value: 0,
			span: 12,
			required: true
		},
		{
			label: t('支付方式'),
			prop: 'payType',
			component: { name: 'el-radio-group', options: options.payType },
			value: 0,
			required: true
		},
		{
			label: t('微信支付码'),
			prop: 'wechatPayCode',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('支付截图'),
			prop: 'payScreenshot',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('总金额'),
			prop: 'totalAmount',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('优惠金额'),
			prop: 'discountAmount',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('支付金额'),
			prop: 'payAmount',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('备注'),
			prop: 'remark',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择商品s'),
			prop: 'GoodIds',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('商品详情'),
			prop: 'productDetails',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('优惠详情'),
			prop: 'discountDetails',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('下单时间'),
			prop: 'orderTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
			},
			span: 12
		},
		{
			label: t('支付时间'),
			prop: 'payTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
			},
			span: 12
		},
		{
			label: t('收货地址'),
			prop: 'address',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('收货人'),
			prop: 'consignee',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('联系电话'),
			prop: 'phone',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('支付截图'),
			prop: 'payImg',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择微信支付商户号'),
			prop: 'mchId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择微信支付订单号'),
			prop: 'transactionId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择微信支付预支付'),
			prop: 'prepayId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('微信支付二维码链接'),
			prop: 'codeUrl',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('微信支付H5链接'),
			prop: 'h5Url',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('微信支付小程序支付参数'),
			prop: 'miniPayParams',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('支付失败原因'),
			prop: 'failReason',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('退款金额'),
			prop: 'refundAmount',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('退款时间'),
			prop: 'refundTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
			},
			span: 12
		},
		{
			label: t('退款单号'),
			prop: 'refundNo',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择店铺'),
			prop: 'shopId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		}
	]
});

// cl-table
const Table = useTable({
	columns: [
		{ label: t('ID'), prop: 'id', minWidth: 80 },
		{ label: t('代理商ID'), prop: 'agentUserId', minWidth: 80 },
		{ label: t('城市'), prop: 'shopCityId', dict: [], minWidth: 120 },
		{ label: t('店铺'), prop: 'shopName', minWidth: 120 },
		// { label: t("销售"), prop: "adminName", minWidth: 120 },
		{ label: t('用户'), prop: 'userNickName', minWidth: 120 },
		{
			label: t('手机号'),
			prop: 'userPhone',
			minWidth: 120,
			formatter(row) {
				return row.userPhone?.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
			}
		},
		// { label: t("手机号"), prop: "userPhone", minWidth: 120 },
		// { label: t("系统订单号"), prop: "orderNo", minWidth: 120 },
		// {
		// 	label: t("支付状态"),
		// 	prop: "payStatus",
		// 	minWidth: 120,
		// 	dict: options.payStatus,
		// },
		// {
		// 	label: t("物流状态"),
		// 	prop: "deliveryStatus",
		// 	minWidth: 120,
		// 	dict: options.deliveryStatus,
		// },
		// {
		// 	label: t("支付方式"),
		// 	prop: "payType",
		// 	minWidth: 120,
		// 	dict: options.payType,
		// },
		// { label: t("微信支付码"), prop: "wechatPayCode", minWidth: 120 },
		// { label: t("支付截图"), prop: "payScreenshot", minWidth: 120 },
		// { label: t("总金额"), prop: "totalAmount", minWidth: 120 },
		// { label: t("优惠金额"), prop: "discountAmount", minWidth: 120 },
		// { label: t("支付金额"), prop: "payAmount", minWidth: 120 },
		// { label: t("备注"), prop: "remark", minWidth: 120 },
		// { label: t("商品IDS"), prop: "GoodIds", minWidth: 120 },
		// { label: t("商品详情"), prop: "productDetails", minWidth: 120 },
		// { label: t("优惠详情"), prop: "discountDetails", minWidth: 120 },
		// {
		// 	label: t("下单时间"),
		// 	prop: "orderTime",
		// 	minWidth: 170,
		// 	sortable: "custom",
		// 	component: { name: "cl-date-text" },
		// },
		// {
		// 	label: t("支付时间"),
		// 	prop: "payTime",
		// 	minWidth: 170,
		// 	sortable: "custom",
		// 	component: { name: "cl-date-text" },
		// },
		// { label: t("收货地址"), prop: "address", minWidth: 120 },
		// { label: t("收货人"), prop: "consignee", minWidth: 120 },
		// { label: t("联系电话"), prop: "phone", minWidth: 120 },
		// { label: t("支付截图"), prop: "payImg", minWidth: 120 },
		// { label: t("微信支付商户号"), prop: "mchId", minWidth: 120 },
		// { label: t("微信支付订单号"), prop: "transactionId", minWidth: 120 },
		// { label: t("微信支付预支付ID"), prop: "prepayId", minWidth: 120 },
		// { label: t("微信支付二维码链接"), prop: "codeUrl", minWidth: 120 },
		// { label: t("微信支付H5链接"), prop: "h5Url", minWidth: 120 },
		// {
		// 	label: t("微信支付小程序支付参数"),
		// 	prop: "miniPayParams",
		// 	minWidth: 120,
		// },
		// { label: t("支付失败原因"), prop: "failReason", minWidth: 120 },
		// { label: t("退款金额"), prop: "refundAmount", minWidth: 120 },
		// {
		// 	label: t("退款时间"),
		// 	prop: "refundTime",
		// 	minWidth: 170,
		// 	sortable: "custom",
		// 	component: { name: "cl-date-text" },
		// },
		// { label: t("退款单号"), prop: "refundNo", minWidth: 120 },
		// { label: t("店铺ID"), prop: "shopId", minWidth: 120 },
		{
			label: t('门店下单时间'),
			prop: 'shopOrderTime',
			minWidth: 170,
			sortable: 'desc',
			component: { name: 'cl-date-text' }
		},
		{
			label: t('厂家下单时间'),
			prop: 'tongkangOrderTime',
			minWidth: 170,
			sortable: 'desc',
			component: { name: 'cl-date-text' }
		},
		{
			label: t('订单状态'),
			prop: 'orderProgress',
			minWidth: 120,
			dict: options.orderProgress
		},
		// {
		// 	label: t("更新时间"),
		// 	prop: "updateTime",
		// 	minWidth: 170,
		// 	sortable: "custom",
		// 	component: { name: "cl-date-text" },
		// },
		{ type: 'op', buttons: ['slot-zhongtian-order-btn'] }
	]
});

// cl-search
const Search = useSearch({
	items: [
		{
			prop: 'agentUserId',
			component: {
				name: 'cl-select',
				props: { options: options.agentUser, placeholder: '代理商' }
			}
		},
		{
			prop: 'shopCityId',
			component: {
				name: 'cl-select',
				props: { options: [], placeholder: '城市' }
			}
		},
		{
			prop: 'shopId',
			component: {
				name: 'cl-select',
				props: { options: [], placeholder: '门店' }
			}
		},
		{
			prop: 'orderProgress',
			component: {
				name: 'cl-select',
				props: { options: options.orderProgress, placeholder: '订单状态' }
			}
		},
		{
			prop: 'userPhone',
			component: {
				name: 'el-input',
				props: { placeholder: '手机号' }
			}
		},
		{
			prop: 'userNickName',
			component: {
				name: 'el-input',
				props: { placeholder: '姓名' }
			}
		}
	]
});

async function getCityList() {
	const res = await service.order.city.getCityList();
	if (res) {
		options.cityList = res;
		// 将Table中shopCityId转换为城市名称
		if (Table.value?.columns) {
			const cityIdColumn = Table.value.columns.find(col => col.prop === 'shopCityId');
			if (cityIdColumn) {
				cityIdColumn.dict = res;
			}
		}
		console.log('Search', Search.value.config.items);
		if (Search.value?.config?.items) {
			const cityIdItem = Search.value.config.items.find(item => item.prop === 'shopCityId');
			if (cityIdItem) {
				cityIdItem.component.props.options = res;
			}
		}
	}
}

async function getShopList() {
	const res = await service.order.shop.getSelectList();
	if (res) {
		if (Search.value?.config?.items) {
			const shopIdItem = Search.value.config.items.find(item => item.prop === 'shopId');
			if (shopIdItem) {
				shopIdItem.component.props.options = res;
			}
		}
	}
}

onMounted(() => {
	getCityList();
	getShopList();
});

// cl-crud
const Crud = useCrud(
	{
		dict: {
			api: {
				page: 'getAgentOrder'
			}
		},
		service: service.agent.agent,
		async onRefresh(params, { next, done, render }) {
			service.agent.agent.queryAgentRelation().then(res => {
				if (res) {
					res.forEach(item => {
						item.children.forEach(child => {
							options.agentUser.push({
								label: child.agentName,
								value: child.agentUserId
							});
						});
					});

					options.agentUser = [];
				}
			});
			if (!params.payStatus) {
				params.payStatus = 1;
			}
			if (!params.orderProgress) {
				params.orderProgress = [0, 1, 2, 3, 4, 5, 6];
			}
			params.isAgent = true;
			Crud.value.params.payStatus = params.payStatus;
			Crud.value.params.orderProcess = params.orderProcess;
			Crud.value.params.isAgent = params.isAgent;
			const { list } = await next(params);
			// 渲染数据
			render(list);
		}
	},
	app => {
		app.refresh();
	}
);

// 导出方法
function onExportData(params: any) {
	return service.agent.agent.getAgentOrder(params).then(res => {
		return res.list;
	});
}

function agentAddOrder(row) {
	currentOrderId.value = row.id;
	currentOrderObj.value = row;
	ZhongtianAddOrderVisible.value = true;
	// console.log('agnetAddOrder', currentOrderObj.value, row, row.orderNo)
}

function agentViewOrder(row) {
	currentOrderId.value = row.id;
	currentOrderObj.value = row;
	ZhongtianViewOrderVisible.value = true;
}

async function viewZhongtianOrder(row) {
	const result = await service.order.merchant.queryOrder({
		order_id: row.id
	});
	console.log(result);
}

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}

function closeDialog() {
	ZhongtianAddOrderVisible.value = false;
	refresh();
}
function closeViewDialog() {
	ZhongtianViewOrderVisible.value = false;
	refresh();
}
function closeCustomerRelationshipDialog() {
	CustomerRelationshipVisible.value = false;
}

function closeCustomerOrderDialog() {
	CustomerOrderVisible.value = false;
	refresh();
}

async function shopAddCustomerOrder() {
	console.log('customerOrder');
	try {
		const res = await service.order.order.createOrderBackendAuth();
		service.agent.agent.getAgentShopList({}).then(res => {
			if (res != null && res != '') {
				shopObj.value = res[0];
			} else {
				ElMessage.error('请先添加店铺');
			}
		});
		console.log('shopObj', shopObj.value);
		CustomerOrderVisible.value = true;
	} catch (error) {
		console.log(error);
		ElMessage.error('亲，您暂无权限');
	}
}

function handleCustomerRelationshipSuccess() {
	// 客情处理成功后的回调
	console.log('客情处理成功');
	refresh();
}

function handleCustomerRelationship(row) {
	// 处理客情处理逻辑
	console.log('处理客情', row);
	currentOrderId.value = row.id;
	currentOrderObj.value = row;
	// 打开客情处理弹窗
	CustomerRelationshipVisible.value = true;
}
</script>
